package com.examination.system.administrator.service.impl;

import com.alibaba.fastjson.JSON;
import com.examination.framework.exception.ExceptionCast;
import com.examination.framework.model.response.CommonCode;
import com.examination.framework.model.response.QueryResponseResult;
import com.examination.framework.model.response.QueryResult;
import com.examination.framework.model.response.ResponseResult;
import com.examination.framework.utils.VisitURLUtil;
import com.examination.system.administration.Employee;
import com.examination.system.administration.ext.IdentityCardAuthenticationInformation;
import com.examination.system.administration.response.*;
import com.examination.system.administrator.dao.EmployeeMapper;
import com.examination.system.administrator.dao.EmployeeRepository;
import com.examination.system.administrator.service.EmployeeService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 寇淇芮
 * @Date 2019/9/15 10:50
 */
@Service
public class EmployeeServiceImpl  implements EmployeeService {
    @Value("${administrator.identityCardAuthentication.appkey}")
    private String APPKEY;
    @Value("${administrator.identityCardAuthentication.url}")
    private String ICAURL;
    @Value("${administrator.mobilePhone.url}")
    private String mobilePhoneUrl;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public QueryResponseResult<Employee> findEmployeeList(Integer page, Integer size) {
        int minSize = 7;
        int maxSize = 25;
        int minPage = 1;
        if (page<minPage){
            page = 1;
        }
        if(size<minSize || size > maxSize){
            size = 10;
        }
        //设置页码和显示条数
        PageHelper.startPage(page,size);
        //查询数据
        Page<Employee> nationPage = employeeMapper.findAll();
        //回写
        QueryResult queryResult = new QueryResult();
        //显示的记录
        queryResult.setList(nationPage.getResult());
        //一共的条数
        queryResult.setTotal(nationPage.getTotal());
        //返回数据
        return new QueryResponseResult(NationCode.SUCCESS,queryResult) ;
    }

    /**
     * 添加员工信息
     * @param employee
     * @return
     */
    @Override
    public AddAdministrationResult addEmployee(Employee employee) throws ParseException {
        //判断信息
        if(StringUtils.isEmpty(employee.getName())){
            ExceptionCast.cast(EmployeeCode.nameCannotBeEmpty);
        }
        //添加信息
        employee.setId(UUID.randomUUID().toString());
        employee.setInTheTime(new Date());
        //添加到数据库
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        employee.setBirthDate(format.parse(identityCardVerificationById(employee.getIdNumber()).getBirth()));
        return employeeMapper.addEmployee(employee)>0 ?new AddAdministrationResult(CommonCode.SUCCESS,employee.getId()):new AddAdministrationResult(CommonCode.FAIL,employee.getId());
    }

    @Override
    public DeleteAdministrationResult deleteEmployeeById(String employeeId, Employee employee) {
        return null;
    }

    @Override
    public ResponseResult editEmployeeById(String employeeId, Employee employee) {
        return null;
    }

    /**
     * 根据身份证号查询是正确
     * @param idNumber
     * @return
     */
    @Override
    public IdentityCardAuthenticationInformation identityCardVerificationById(String idNumber) {
        ICAURL = ICAURL+"?"+APPKEY+"&idcard="+idNumber;
        List<IdentityCardAuthenticationInformation> result = new ArrayList<>();
        String msg = null;
        try {
            msg = VisitURLUtil.getData(ICAURL, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
         ProvinceResponse<IdentityCardAuthenticationInformation> provinceResponse = JSON.parseObject(msg, ProvinceResponse.class);
        msg = JSON.toJSONString(provinceResponse.getResult());
        msg = msg.substring(1,msg.length()-1);
        return  JSON.parseObject(msg, IdentityCardAuthenticationInformation.class);
    }

    @Override
    public ResponseResult checkCellPhoneNumber(String cellPhoneNumber) {
        if (StringUtils.isEmpty(cellPhoneNumber)) {
            ExceptionCast.cast(EmployeeCode.cellPhoneNumberIsEmpty);
        }
        return verificationPhone(cellPhoneNumber)==false?new ResponseResult(CommonCode.SUCCESS) :new ResponseResult(CommonCode.FAIL);
    }

    @Override
    public AddAdministrationResult updateEmployee(Employee employee) {

        Assert.notNull(employee,"员工数据不能为空");
        if(StringUtils.isEmpty(employee.getId())){
            ExceptionCast.cast(EmployeeCode.MODIFYING_DATA_EXCEPTIONS);
        }
        //判断更新的数据是否存在
        Employee one = this.findEmployeeById(employee.getId());
         if(one == null){
             ExceptionCast.cast(EmployeeCode.MODIFYING_DATA_EXCEPTIONS);
         }
        /*BeanUtils.copyProperties(employee,one);
        return employeeRepository.save(one)==null?new AddAdministrationResult(CommonCode.FAIL,employee.getId()):new AddAdministrationResult(CommonCode.SUCCESS,employee.getId());*/
       ;
        return   employeeMapper.upateEmployee(employee)== 0?new AddAdministrationResult(CommonCode.FAIL,employee.getId()):new AddAdministrationResult(CommonCode.SUCCESS,employee.getId());
    }
    /**
     * 查询单个数据
     */
    @Override
    public Employee findEmployeeById(String id){
        Optional<Employee> optional = employeeRepository.findById(id);
        if(optional.isPresent()){
            return  optional.get();
        }
        return  null;
    }

    /**
     * 判断是否是有效手机号
     * @param phone  手机号
     * @return 是否存在
     */
    private boolean verificationPhone(String phone)  {
        ZoneResult zoneResult = null;
        try {
            String msg = VisitURLUtil.getData(mobilePhoneUrl + phone, "GBK");
             zoneResult = JSON.parseObject(msg.substring(msg.indexOf("=")+1), ZoneResult.class);
        } catch(Exception e){
            e.printStackTrace();
        }

        return StringUtil.isNotEmpty(zoneResult.getMts())? false :true;
    }
}
